<template>
  <el-upload
    :file-list="fileList"
    :action="url" 
    list-type="picture-card"
    :before-upload="beforeUploadHandle" 
    :on-success="successHandle"
  >
    <el-icon><Plus /></el-icon>
    <template #file="{ file }">
      <div :class="file.isRecommend === 1 ? 'activeClass': ''">
        <small-image class="el-upload-list__item-thumbnail" :style="`--my-width: ${100}%; --my-height: ${100}%;`" :url="file.url" />
        <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
          >
            <el-icon><zoom-in /></el-icon>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="checkHandle(file)"
          >
            <el-icon><Check /></el-icon>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file)"
          >
            <el-icon><Delete /></el-icon>
          </span>
        </span>
      </div>
    </template>
  </el-upload>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { Plus } from "@element-plus/icons-vue";
import app from "@/constants/app";
import { getToken } from "@/utils/cache";
import { IObject } from "@/types/interface";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
import SmallImage from "@/components/small-image/index.vue"
import type { UploadProps, UploadUserFile } from "element-plus";
const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);
const url = ref("");
const num = ref(0);
const belongId = ref(null);
const imageBelong:any = ref(null);
const fileList:any = ref<IObject[]>();

const init = (id:any, imageBelongType:number, fileLists:any[]) => {
  url.value = `${app.api}/oss/file/upload?access_token=${getToken()}`;
  num.value = 0;
  fileList.value = fileLists;
  belongId.value = id == "" ? null : id;
  imageBelong.value = imageBelongType;
};

const dialogImageUrl = ref("");
const dialogVisible = ref(false);

// 自动删除fileList.value
const handleRemove: UploadProps["onRemove"] = (uploadFile) => {
  deleteImageRequest(uploadFile);
};

const _getUrl = (item:any) => {
  return item.response ? item.response.data.url : item.url;
}

const checkHandle = (uploadFile:any) => {
  fileList.value = fileList.value.map((item:any) => {
    item["isRecommend"] = 0;
    if (uploadFile.uid === item.uid) {
      item["isRecommend"] = 1;
    }
    return item;
  });

  emit("refreshDataList", getFileLists());
}

const getFileLists = () => {
  const params:any = fileList.value.map((item:any) => {
    return {imageId: item.imageId, name: item.name, size: item.size, imageType: item.imageType ? item.imageType : item.raw.type, belongId: belongId.value, imageBelong: imageBelong.value, imageId: item.imageId, url: _getUrl(item), isRecommend: item.isRecommend == 1 ? 1 : 0};
  })
  return params;
}

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

const deleteImageRequest = (file:any) => {
  fileList.value = fileList.value.filter((item:any) => {
      return file.uid !== item.uid;
    });
    emit("refreshDataList", getFileLists());
};

// 上传之前
const beforeUploadHandle = (file: IObject) => {
  if (file.type !== "image/jpg" && file.type !== "image/jpeg" && file.type !== "image/png" && file.type !== "image/gif") {
    ElMessage.error(t("upload.tip", { format: "jpg、png、gif" }));
    return false;
  }
  num.value++;
};
// 上传成功
const successHandle = async (res: IObject, file: IObject, list: IObject[]) => {
  if (res.code !== 200) {
    return ElMessage.error(res.message);
  }
  // 更新
  fileList.value = list;
  console.log(file);
  console.log(list);
  num.value--;
  if (num.value === 0) {
    ElMessage.success({
      message: t("prompt.success"),
      duration: 500,
      onClose: () => {
        emit("refreshDataList", getFileLists());
      }
    });
  }
};

defineExpose({
  init
});
</script>
<style lang="less" scoped>
.el-upload-list__item {
  > div {
    width: 100%;
    height: 100%;
  }
  > div.activeClass {
    border: 4px solid green;
  }
}
</style>
